<template>
  <div ref="chartContainer" style="width: 100%; height: 100%"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';
import type { ECharts, EChartsOption } from 'echarts';


const chartContainer = ref<HTMLElement | null>(null);
let chart: ECharts | null = null;

// Sample data for the line chart
const studentData = [45, 65, 68, 65, 90, 60, 85];
const averageData = [50, 40, 42, 45, 55, 78, 85];
const timeLabels = ['00:00', '01:00', '02:00', '04:00', '05:00', '06:00', '07:00'];

onMounted(() => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value);
    renderChart();

    window.addEventListener('resize', handleResize);
  }
});

onUnmounted(() => {
  if (chart) {
    chart.dispose();
    window.removeEventListener('resize', handleResize);
  }
});

const handleResize = (): void => {
  if (chart) {
    chart.resize();
  }
};

const renderChart = (): void => {
  if (!chart) return;

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis',
      formatter: function(params: unknown | unknown[]) {
        // 确保 params 是数组
        const paramsArray = Array.isArray(params) ? params : [params];

        if (paramsArray.length === 0) return '';

        const time = paramsArray[0].axisValue?.toString() || '';
        let result = `${time}<br/>`;

        paramsArray.forEach((param) => {
          const color = param.color || '';
          const seriesName = param.seriesName || '';
          const value = param.value;
          result += `<span style="display:inline-block;margin-right:4px;border-radius:50%;width:10px;height:10px;background-color:${color};"></span>`;
          result += `${seriesName}: ${value}<br/>`;
        });

        return result;
      }
    },
    legend: {
      data: ['个人成绩', '班级平均'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: timeLabels,
      axisLine: {
        lineStyle: {
          color: '#E0E0E0'
        }
      }
    },
    yAxis: {
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#E0E0E0'
        }
      },
      min: 0,
      max: 120,
      interval: 20
    },
    series: [
      {
        name: '个人成绩',
        type: 'line',
        smooth: true,
        data: studentData,
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 3
        },
        symbolSize: 8
      },
      {
        name: '班级平均',
        type: 'line',
        smooth: true,
        data: averageData,
        itemStyle: {
          color: '#909399'
        },
        lineStyle: {
          width: 3
        },
        symbolSize: 8
      }
    ]
  };

  chart.setOption(option);
};
</script>
